package cn.sccl.mybatis.junt;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import cn.sccl.mybatis.mapper.UserMapper;
import cn.sccl.mybatis.pojo.User;

/**
 * @author 饶爽
 * @time 2019年9月21日 下午5:04:59
 * @version 1.0.0
 * User的mapper动态代理测试
*/
public class MybatisMapperTest {
    public SqlSessionFactory sqlSessionFactory;
    @Before
    public void before() throws Exception {
        //加载核心配置文件
        String resource = "sqlMapConfig.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
    }
    @Test
    public void testMapper() throws Exception {
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        //SqlSEssion帮我生成一个实现类  （给接口）
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        
        User user = userMapper.findUserById(10);
        System.out.println(user);
        sqlSession.close();
    }
    @Test
    public void testMapper2() throws Exception {
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        //SqlSEssion帮我生成一个实现类  （给接口）
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        
        List<User> list = userMapper.queryUserByUsername("张");
        for (User user : list) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    @Test
    public void testMapper3() throws Exception {
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        //SqlSEssion帮我生成一个实现类  （给接口）
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        // 创建保存对象
        User user = new User();
        user.setUsername("刘小备");
        user.setBirthday(new Date());
        
        userMapper.insertUser(user);
        System.out.println(user);
        // 和spring整合后由spring管理
        sqlSession.commit();
        sqlSession.close();
    }
}
